package cn.zwx.activiti.example.conifig;

import cn.hutool.core.collection.CollectionUtil;
import cn.zwx.activiti.example.mapper.UserMapper;
import cn.zwx.activiti.example.model.po.UserPO;
import cn.zwx.activiti.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.core.userdetails.User;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @projectName:activiti-example
 * @see:cn.zwx.activiti.example.conifig
 * @author:zhangwenxue
 * @createTime:2021/5/6 16:00
 * @version:1.0
 */
@Configuration
public class SecurityConfig {

    private Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    @Autowired
    private UserService userService;

    @Bean
    public UserDetailsService myUserDetailsService() {

        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        List<UserPO> userList = userService.selectAll();
        if (CollectionUtil.isEmpty(userList)){
            logger.error("未查询到数据用户信息");
            return inMemoryUserDetailsManager;
        }

        String[][] usersGroupsAndRoles  = new String[userList.size()][3];
         for (int i = 0; i < userList.size(); i++) {
            UserPO userPO = userList.get(i);
            String[] userArr =  new String[3];
            userArr[0] = userPO.getUserName();
            userArr[1] =  userPO.getPassword();
            userArr[2] =  userPO.getRoles();
            usersGroupsAndRoles[i] = userArr;
        }
        for (String[] user : usersGroupsAndRoles) {
            List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
            logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]");
            inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]),
                    authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList())));
        }


        return inMemoryUserDetailsManager;

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
